package com.markhsiu.common.memory;

/**
 * 最小数据块
 * @author Mark Hsiu
 *
 */
public class MMBlock {

	public static final int LENGTH_MAX = 1024;//1024byte 
	private int offset;//内存的位置
	private int chunkIndex = 0;//在chunk中被使用数组的位置0..n
	private MMChunk chunk;
	
	public MMBlock builder(MMChunk chunk, int offset){
		if( offset < 0){
			throw new IllegalArgumentException();
		}
		this.chunk = chunk;
		this.offset = offset;
		return this;
	}
	
	public int length(){
		return LENGTH_MAX;
	}
	
	public int offset(){
		return offset;
	}
	
	public int chunkIndex(){
		return chunkIndex;
	}
	
	public boolean used(){
		return chunkIndex > 0;
	}
	
	public MMBlock setChunkIndex(int index){
		this.chunkIndex = index;
		return this;
	}
	
	 void free(){
		chunk.free(this);
	}
	 
	 @Override
	 public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("{bcode:");
			sb.append(hashCode());
			sb.append("},{offset:");
			sb.append(offset);
			sb.append("},{chunkIndex:");
			sb.append(chunkIndex);
			sb.append("},{chunk:");
			sb.append(chunk);
			sb.append("}");
			return sb.toString();	
		}
	
}
